import io, os;

def GetString(s, encoding):
	if isinstance(s, str):
		return s;
	try:
		res = s.decode(encoding);
		return res;
	except:
		return None;


def ReadFilePart(filename, size=1024):
	if (not isinstance(filename, str)):
		return None;
	try:
		f = io.open(filename, "rb");
	except:
		return None;
	s = f.read(size);
	f.close();
	res = GetString(s, 'utf8');
	if (res == None):
		res = GetString(s, 'cp1251');
	if (res == None):
		res = GetString(s, 'cp866');
	if (res == None):
		res = s.decode('utf8', 'replace');
	return res;	

def DeleteFile(name):
	try:
		os.remove(name);
		return True;
	except OSError:
		return False;

def SaveFile(path, fileobj):
	if (path == None): 
		return False;
	if (fileobj == None):
		return False;
	try:
		path = str(path);
	except:
		return False;
	TryMakeDir(path);
	if (not hasattr(fileobj, 'filename') or not hasattr(fileobj, 'file') or fileobj.filename == None):
		return False;
	try:
		f = open(path + fileobj.filename, "wb");
		f.write(fileobj.file.read());
		f.close();
	except IOError:
		return False;
	return True;

def RenameFile(name1, name2):
	try:
		os.rename(name1, name2);
		return True;
	except:
		return False;

def ChangeFilePart(filename, part, part_size):
	try:
		f = open(filename, "rb");
		f.read(part_size);
		last_text = f.read();
		f.close();
		begin = str(part[:part_size]).encode('utf8');
		f = open(filename, "wb");
		f.write(begin);
		f.write(last_text);
		f.close();
		return True;
	except:
		return False;
	
def TryMakeDir(path):
	try:
		os.mkdir(path);
	except:
		pass
